package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
	"sync"
)

type NacosClientWrapper struct {
	confString string
	lk         sync.RWMutex
	clt        config_client.IConfigClient
}

func NewNacosClient() *NacosClientWrapper {
	return &NacosClientWrapper{}
}

func (w *NacosClientWrapper) resetConnection() {
	if w.clt != nil {
		w.clt.CloseClient()
		w.clt = nil
	}
}

// reconnect 尝试建立新的 gRPC 连接并创建客户端存根
func (w *NacosClientWrapper) reconnect() (config_client.IConfigClient, error) {
	w.resetConnection()

	//rval, err := NewRedisClient(w.redisConnString)
	//if err != nil {
	//	return nil, err
	//}
	//w.clt = rval.(redis.UniversalClient)
	return w.clt, nil
}

// getOrCreateClient 获取当前可用的客户端存根，如果连接失效则自动重连
func (w *NacosClientWrapper) getOrCreateClient() (clt config_client.IConfigClient, err error) {
	w.lk.RLock()
	if w.clt != nil {
		clt = w.clt
		w.lk.RUnlock()
		return
	}
	w.lk.RUnlock()

	w.lk.Lock()
	defer w.lk.Unlock()
	return w.reconnect()
}

func (this *NacosClientWrapper) UpdateConfig(s string) {
	this.lk.Lock()
	defer this.lk.Unlock()
	if this.confString != s {
		this.confString = s
		this.resetConnection()
	}
}
